package oss

import (
	"cat_mouse/core/settings"
	"cat_mouse/infra/utils"
	"cat_mouse/infra/utils/log"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"sync"
)

var (
	aLiYunOssClient *ALiYunClient
	aLiYunOssOnce   sync.Once
)

type ALiYunClient struct {
}

func GetALiYunClient() *ALiYunClient {
	aLiYunOssOnce.Do(func() {
		aLiYunOssClient = &ALiYunClient{}
	})
	return aLiYunOssClient
}

// GetUploadCredential 参考文档 https://help.aliyun.com/zh/oss/developer-reference/use-temporary-access-credentials-provided-by-sts-to-access-oss
func (a *ALiYunClient) GetUploadCredential() (*sts.AssumeRoleResponse, error) {
	client, err := sts.NewClientWithAccessKey(
		settings.Config.ALiYunOss.RegionId,
		settings.Config.ALiYunOss.AccessKey,
		settings.Config.ALiYunOss.SecretKey,
	)
	if err != nil {
		return nil, err
	}
	//构建请求对象。
	request := sts.CreateAssumeRoleRequest()
	request.Scheme = "https"
	//设置参数。关于参数含义和设置方法，请参见《API参考》。
	request.RoleArn = settings.Config.ALiYunOss.RoleArn                                //步骤三获取的角色ARN
	request.RoleSessionName = settings.Config.ALiYunOss.RoleSessionName                //步骤三中的RAM角色名称
	request.DurationSeconds = requests.Integer(utils.GetSysCfg().ALiYunOssTokenExpire) //最小设置为900
	//发起请求，并得到响应。
	response, err := client.AssumeRole(request)
	if err != nil {
		return nil, err
	}
	return response, nil
}

func (a *ALiYunClient) DelObject(bucketName, objectName string) error {
	var (
		client *oss.Client
		bucket *oss.Bucket
		err    error
	)
	client, err = oss.New(
		settings.Config.ALiYunOss.Endpoint,
		settings.Config.ALiYunOss.AccessKey,
		settings.Config.ALiYunOss.SecretKey,
	)
	if err != nil {
		log.Logger.Error(err)
		return err
	}
	if bucket, err = client.Bucket(bucketName); err != nil {
		log.Logger.Error(err)
		return err
	}
	if err = bucket.DeleteObject(objectName); err != nil {
		log.Logger.Error(err)
		return err
	}
	return err
}
